// 简单的MQTT测试客户端
const mqtt = require('mqtt');

console.log('🔌 正在连接MQTT服务器...');

const client = mqtt.connect('mqtt://localhost:1883', {
    clientId: 'test-client-' + Math.random().toString(16).substr(2, 8)
});

client.on('connect', () => {
    console.log('✅ MQTT连接成功！');
    
    // 订阅主题
    client.subscribe('heart', (err) => {
        if (!err) {
            console.log('✅ 订阅heart主题成功');
        }
    });
    
    client.subscribe('kaihong/devices/cmd/put', (err) => {
        if (!err) {
            console.log('✅ 订阅kaihong/devices/cmd/put主题成功');
        }
    });
    
    // 发送测试消息
    setTimeout(() => {
        client.publish('kaihong/devices/cmd/put', 'Test message from Node.js client');
        console.log('📤 发送测试消息');
    }, 1000);
    
    setTimeout(() => {
        client.publish('heart', 'heartbeat test');
        console.log('💓 发送心跳测试');
    }, 2000);
});

client.on('message', (topic, message) => {
    console.log(`📨 收到消息 - 主题: ${topic}, 内容: ${message.toString()}`);
});

client.on('error', (error) => {
    console.error('❌ MQTT连接错误:', error);
});

client.on('close', () => {
    console.log('🔌 MQTT连接已关闭');
});

// 10秒后断开连接
setTimeout(() => {
    client.end();
    process.exit(0);
}, 10000);